<template>
	<div id="app">
		<div class="chat-container">
			<div class="message-list">
			    <div 
			        v-for="(msg, index) in messages" 
			        :key="msg.messageId" 
			        class="message-item" 
			        :class="{'self': msg.isSelf, 'other': !msg.isSelf}"
			    >
			        <div class="message-time" v-if="shouldShowTime(index)">{{ formatTime(msg.timestamp) }}</div>
			        <div class="message-wrapper">
				        <div class="avatar-wrapper">
				            <div class="sender-name">{{ msg.senderNickname }}</div>
				            <div class="avatar">
				                <image :src="msg.isSelf ? userInfo.avatar : consultantInfo.avatar" mode="aspectFill"></image>
				            </div>
				        </div>
				        <div class="message-content">
				            <div class="message-text">
				                {{ msg.payload.text }}
				            </div>
				        </div>
			        </div>
			    </div>
			</div>
			<div class="input-area">
				<input v-model="messageText" placeholder="输入消息..." @keyup.enter="sendMessage" class="input-box" />
				<button @click="sendMessage" class="send-btn">发送</button>
			</div>
		</div>
		
		<!--评分弹窗-->
		<u-popup :show="showRating" mode="center" bgColor="transparent">
			<view class="popupwin">
				<div class="popTitle">
					为咨询师打个分吧
				</div>
				<div class="close" @click="getHide">
					<u-icon name="close"></u-icon>
				</div>
				<div class="score">
					<div class="title">整体咨询</div>
					<u-rate :gutter="0" count="5" active-color="#fcdc0d" inactive-color="#d8d8d8" v-model="value1">
					</u-rate>
				</div>
				<div class="submit" @click="submitRating()">
					提交
				</div>
			</view>
		</u-popup>
		
	</div>
</template>

<script>
import GoEasy from 'goeasy'; // 确保你已经安装了 goeasy SDK


export default {
    data() {
        return {
            messages: [],
            messageText: '',
            consultantInfo: {
                avatar: "/static/logo.png",
                name: "加载中..."
            },
            receiverId: '',
            userInfo: {
                avatar: "/static/logo.png",
                name: "加载中...",
            },
            senderId: '',
			startTime: '',
			
			//评分所用
			showRating: false,
			value1: 3
        };
    },
    async onLoad(options) {
        this.goeasy = this.$goeasy;
        if (!this.goeasy) {
            console.error('GoEasy 未初始化');
            return;
        }

        try {
			const startTime = Number(options.startTime); 
			this.startTime = startTime;

            if (options.consultantToken) {
                await this.getConsultantInfo(options.consultantToken);
            }
            await this.getUserInfo();
            
            if (this.senderId) {
                this.connectToGoEasy();
            } else {
                console.error("无法获取 senderId，连接 GoEasy 失败");
            }
        } catch (error) {
            console.error("初始化失败", error);
        }
		
		this.getHistoryMessages()
    },
    
    onShow() {
        this.scrollToBottom();
    },
    
    onUnload() {
        if (this.goeasy) {
            this.goeasy.disconnect();
            console.log("GoEasy 连接已断开");
        }
    },
    
    onBackPress() {
        if (this.goeasy) {
            this.goeasy.disconnect();
            console.log("GoEasy 连接已断开");
        }
        return false;
    },
	computed:{
		isDev(){
			return process.env.NODE_ENV === 'development'
		}
	},
		methods: {
			submitRating(){
				this.showRating = false;
				const res = uniCloud.callFunction({
					name:"updateRating",
					data:{
						uniIdToken:uni.getStorageSync("uni_id_token"),
						consultantId:this.receiverId,
						rating:this.value1
					}
				})
				console.log(this.receiverId,res)
			},
			getHide() {
				this.showRating = false
			},
			
			async getUserInfo() {
				try {
					const res = await uniCloud.callFunction({
						name: "getUserInfo",
						data: {
							uniIdToken: uni.getStorageSync('uni_id_token')
						}
					});
					if (res.result.code === 0 && res.result.data) {
						// 获取头像临时访问地址
						if (res.result.data.avatar_file?.url) {
							const tempFileRes = await uniCloud.getTempFileURL({
								fileList: [res.result.data.avatar_file.url]
							});
							this.userInfo.avatar = tempFileRes.fileList?.[0]?.tempFileURL || '/static/logo.png';
						} else {
							this.userInfo.avatar = '/static/logo.png';
						}
						this.userInfo.name = res.result.data.nickname;
						this.senderId = res.result.data.uid;
					} else {
						console.error("获取用户信息失败:", res.result.message);
					}
				} catch (error) {
					console.error("云函数调用失败:", error);
				}
			},
			async getConsultantInfo(token) {
				try {
					const res = await uniCloud.callFunction({
						name: "getConsultantInfo",
						data: {
							uniIdToken: token
						}
					});
					if (res.result.code === 0 && res.result.data) {
						this.consultantInfo.avatar = res.result.data.avatar;
						this.consultantInfo.name = res.result.data.name;
						this.receiverId = res.result.data.uid;
					} else {
						console.error("获取顾问信息失败:", res.result.message);
					}
				} catch (error) {
					console.error("云函数调用失败:", error);
				}
			},

			connectToGoEasy() {
				console.log('senderId',this.senderId)
				this.goeasy.connect({
					id: this.senderId || '未知用户',
					data: {
						avatar: this.userInfo.avatar,
						name: this.userInfo.name // 使用获取到的用户昵称
					},
					onSuccess: () => {
						console.log('GoEasy connected successfully.');
						this.getHistoryMessages();
						this.listenForPrivateMessages();
					},
					onFailed: (error) => {
						console.error('Failed to connect GoEasy, code:' + error.code + ', error:' + error
							.content);
					},
					onProgress: (attempts) => {
						console.log('GoEasy is connecting', attempts);
					}
				});
			},
			scrollToBottom() {
				// this.$nextTick(() => {
				// 	setTimeout(() => {
				// 		// TODO: document is undefined in miniapp
				// 		const messageList = document.querySelector('.message-list');
				// 		if (messageList) {
				// 			messageList.scrollTop = messageList.scrollHeight;
				// 		}
				// 	}, 100);
				// });
			},
			formatTime(timestamp) {
				if (!timestamp) return '';
				const date = new Date(timestamp);
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			},
			
			getHistoryMessages() {
				if (!this.goeasy?.im) {
					console.error("GoEasy 未初始化");
					return;
				}
				const im = this.goeasy.im;
			
				im.history({
					id: this.receiverId,
					type: GoEasy.IM_SCENE.PRIVATE,
					lastTimestamp: null, // 不传时间戳，默认拿最新的往前查
					limit: 30, // 拿够多条，保证筛选后还有剩
					onSuccess: (result) => {
					    console.log("获取历史消息成功", result);
					    if (result.code === 200 && result.content.length > 0) {
							
					        const startTime = Number(this.startTime); // 确保 startTime 是数字
					        // 遍历每条消息并检查 timestamp
					        const filteredMessages = result.content.filter(msg => {

					            // 确保 timestamp 存在且为数字
					            if (typeof msg.timestamp === "number" && msg.timestamp >= this.startTime) {
					                return true;
					            }
					            return false;
					        });
							
					
					        this.messages = filteredMessages.map(msg => ({
					            messageId: msg.messageId,
					            senderId: msg.senderId,
					            senderNickname: msg.senderId === this.senderId ? this.consultantInfo.name : this.userInfo.name,
					            payload: { text: msg.payload.text },
					            isSelf: msg.senderId === this.senderId,
								timestamp: msg.timestamp
					        }));
							this.scrollToBottom();
					    } else {
					        this.messages = [];
					    }
					},
			
					onFailed: (error) => {
						console.error('获取历史消息失败, code:' + error.code + ', error: ' + error.content);
					}
				});
			},
			sendMessage() {
			    if (!this.goeasy?.im) { // 防止报错
			        uni.showToast({
			            title: '聊天未就绪',
			            icon: 'none'
			        });
			        return;
			    }
			    if (!this.messageText) return; // 如果消息为空，直接返回
				console.log(this.receiverId)
			    const im = this.goeasy.im;
			    const textMessage = im.createTextMessage({
			        text: this.messageText, // 消息内容
			        to: {
			            type: GoEasy.IM_SCENE.PRIVATE, // 私聊
			            id: this.receiverId, // 接收方用户ID
			            data: {
			                avatar: this.consultantInfo.avatar,
			                nickname: this.consultantInfo.name
			            }
			        }
			    });
			
			    // 发送消息
			    im.sendMessage({
			        message: textMessage,
			        onSuccess: (message) => {
			            this.messages.push({
			                messageId: message.messageId,
			                senderId: this.senderId, // 记录发送者ID
			                senderNickname: this.userInfo.name, // 发送者昵称
			                payload: { text: this.messageText },
			                isSelf: true, // 发送的是自己
			                timestamp: Date.now()
			            });
			            console.log('Private message sent successfully.', message);
			            this.messageText = ''; // 清空输入框
			            this.scrollToBottom();
			        },
			        onFailed: (error) => {
			            console.log('Failed to send private message, code:' + error.code + ', error: ' + error.content);
			        }
			    });
			},
			listenForPrivateMessages() {
			    const im = this.goeasy.im;
			    im.on(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, (message) => {
			        console.log('Received private message:', message);
			        this.messages.push({
			            messageId: message.messageId,
			            senderId: message.senderId,
			            senderNickname: message.senderId === this.senderId ? this.userInfo.name : this.consultantInfo.name,
			            payload: {
			                text: message.payload.text
			            },
			            isSelf: message.senderId === this.senderId,
			            timestamp: message.timestamp
			        });
			        this.scrollToBottom();
			    });
			},
			shouldShowTime(index) {
				if (index === 0) return true; // 第一条消息总是显示时间
				const currentTime = this.messages[index].timestamp;
				const prevTime = this.messages[index - 1].timestamp;
				const timeDiff = Math.abs(currentTime - prevTime);
				return timeDiff > 5 * 60 * 1000; // 5分钟 = 5 * 60 * 1000 毫秒
			}
		},

		beforeDestroy() {
			const im = this.goeasy.im;
			im.off(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED); // 取消监听私聊消息
		}
	};
</script>

<style scoped lang="scss">
/* 	#app {
		font-family: Avenir, Helvetica, Arial, sans-serif;
		text-align: center;
		color: #2c3e50;
		margin-top: 60px;
	} */

	.chat-container {
		/* padding: 20rpx; */
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.message-list {
		height: calc(100vh - 140rpx);
		overflow-y: auto;
		/* margin-bottom: 120rpx; */
		padding: 20rpx;
	}

	.message-item {
		display: flex;
		flex-direction: column;
		margin-bottom: 30rpx;
		align-items: flex-start;
	}

	.message-item.self {
		align-items: flex-end;
	}

	.message-wrapper {
		display: flex;
		align-items: flex-start;
		width: 100%;
	}

	.message-item.self .message-wrapper {
		flex-direction: row-reverse;
	}

	.avatar-wrapper {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-right: 20rpx;
	}

	.message-item.self .avatar-wrapper {
		margin-right: 0;
		margin-left: 20rpx;
	}

	.sender-name {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 8rpx;
		text-align: center;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		overflow: hidden;
		flex-shrink: 0;
	}

	.avatar image {
		width: 100%;
		height: 100%;
	}

	.message-content {
		max-width: 60%;
		background-color: #ffffff;
		padding: 20rpx;
		border-radius: 4rpx 20rpx 20rpx 20rpx;
		position: relative;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
		margin-top: 28rpx;
	}

	.message-item.self .message-content {
		background-color: #95ec69;
		border-radius: 20rpx 4rpx 20rpx 20rpx;
	}

	.message-text {
		font-size: 28rpx;
		line-height: 1.5;
		word-break: break-all;
	}

	.message-time {
		font-size: 20rpx;
		color: #999;
		text-align: center;
		margin-bottom: 8rpx;
		width: 100%;
	}

	.message-item.self .message-time {
		text-align: center;
	}

	.input-area {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		padding: 20rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.input-box {
		flex: 1;
		background-color: #f5f5f5;
		border-radius: 40rpx;
		padding: 20rpx 30rpx;
		margin-right: 20rpx;
	}

	.send-btn {
		width: 120rpx;
		height: 60rpx;
		background-color: #6c8eef;
		border-radius: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #ffffff;
		font-size: 28rpx;
	}

	.send-btn .u-icon {
		color: #ffffff;
	}

	.back-button {
		position: fixed;
		bottom: 160rpx;
		left: 50%;
		transform: translateX(-50%);
		background-color: #6c8eef;
		color: #ffffff;
		border: none;
		padding: 16rpx 40rpx;
		border-radius: 30rpx;
		font-size: 28rpx;
		box-shadow: 0 4rpx 12rpx rgba(108, 142, 239, 0.3);
		z-index: 100;
	}

	.back-button:active {
		transform: translateX(-50%) translateY(2rpx);
		box-shadow: 0 2rpx 6rpx rgba(108, 142, 239, 0.2);
	}
	
	.popupwin {
		width: 630rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		// height: 750rpx;
		background: #FFFFFF;
		opacity: 1;
		position: relative;
		z-index: 1000;
	}
	
	.popTitle {
		font-family: PingFangSC-Medium;
		font-size: 34rpx;
		color: #333333;
		text-align: center;
		font-weight: 500;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-wrap: nowrap;
		flex-direction: row;
		align-content: flex-start;
		padding-top: 40rpx;
	}
	
	.close {
		position: absolute;
		right: 30rpx;
		top: 40rpx;
		z-index: 10;
	}
	
	.submit {
		width: 411rpx;
		height: 90rpx;
		background-image: linear-gradient(179deg, #00aaff 1%, #00aaff 100%);
		border-radius: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-wrap: nowrap;
		flex-direction: row;
		align-content: flex-start;
		font-family: PingFangSC-Medium;
		font-size: 32rpx;
		color: #FFFFFF;
		font-weight: 500;
		margin: 0 auto;
		margin-top: 50rpx;
		margin-bottom: 50rpx;
	}
	
	.score {
		margin-left: 80rpx;
		margin-right: 80rpx;
		margin-top: 50rpx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		flex-wrap: nowrap;
		flex-direction: row;
		align-content: flex-start;
		
			.title {
				font-family: PingFangSC-Regular;
				font-size: 26rpx;
				color: #000000;
				font-weight: 400;
				margin-right: 20rpx;
			}
	}
	
</style> 